/**
 * 
 */
package com.csair.youth.web.action;

import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.csair.youth.constant.Constant;
import com.csair.youth.database.Notice;
import com.csair.youth.service.impl.NoticeServiceImpl;

/**
 * @author mickey
 *
 */
public class NoticeEditAction extends _BaseAction {
	private Notice item;
	private NoticeServiceImpl service;

	public Notice getItem() {
		return item;
	}
	public void setItem(Notice item) {
		this.item = item;
	}
	public NoticeServiceImpl getService() {
		return service;
	}
	public void setService(NoticeServiceImpl service) {
		this.service = service;
	}
	
	public String execute(){
		if(item != null && !StringUtils.isEmpty(item.getId())){
			//从数据库获取...
			item = service.getNotice(item.getId());
		}
		else item = new Notice();
		return SUCCESS;
	}
	
	public String save(){
		if(item == null) {
			this.setMessage("公告对象为空.");
			return INPUT;
		}
		if(!validInput(item)) return INPUT;
		if(StringUtils.isEmpty(item.getId())){
			//如果是新建，则要加入创建人..
			item.setPublishIp(this.getServletRequest().getRemoteAddr());
			item.setPublishTime(new Date());
			item.setPublishUserId((String)this.getSessionAttribute(Constant.USER_ID_SESSION_KEY));
			item.setLastModifyIp(item.getPublishIp());
			item.setLastModifyTime(item.getPublishTime());
			item.setLastModifyUserId(item.getPublishUserId());
		}
		else{
			Notice tmpItem = service.getNotice(item.getId());
			if(tmpItem == null){
				this.setMessage("根据给定id找不到指定公告!");
				return INPUT;
			}
			item.setPublishIp(tmpItem.getPublishIp());
			item.setPublishTime(tmpItem.getPublishTime());
			item.setPublishUserId(tmpItem.getPublishUserId());
			item.setLastModifyIp(this.getServletRequest().getRemoteAddr());
			item.setLastModifyTime(new Date());
			item.setLastModifyUserId((String)this.getSessionAttribute(Constant.USER_ID_SESSION_KEY));
		}
		service.saveNotice(item);
		this.setMessage("已成功保存公告.");
		return SUCCESS;
	}
	
	private boolean validInput(Notice item){
		if(item == null) return false;
		boolean allValid = true;
		StringBuffer msgBf = new StringBuffer();
		String title = item.getTitle();
		if(StringUtils.isEmpty(title) || StringUtils.length(title)> 120){
			msgBf.append("标题不能为空且必须在120个字符内<br/>");
			allValid = false;
		}
		String content = item.getContent();
		if(StringUtils.isEmpty(content)){
			msgBf.append("公告内容不能为空<br/>");
			allValid = false;
		}
		this.setMessage(msgBf.toString());
		return allValid;
	}
}
